<?php

namespace App\Http\Controllers\Api\v1\Everyday;
use App\Http\Controllers\Api\BaseController;
use Illuminate\Support\Facades\Input;
use Illuminate\Http\Request;
use App\Models\Api\Recode;
use App\Exceptions\ApiException;
use App\Tools\Astrolog\Astrolog;
use App\Http\Controllers\Api\v1\Everyday\ActiveController;
use App\Http\Controllers\Api\v1\Everyday\Active_devController;
use App\Http\Controllers\Api\v1\Everyday\AvoidController;
use App\Http\Controllers\Api\v1\Everyday\LuckdisastersController;
use App\Http\Controllers\Api\v1\Everyday\LuckythingController;
use App\Http\Controllers\Api\v1\Everyday\TopicController;
use App\Http\Controllers\Api\v1\Everyday\SayingController;
use App\Http\Controllers\Api\v1\Everyday\SuitableController;
use App\Http\Controllers\Api\v1\Everyday\TipsController;
use App\Http\Controllers\Api\v1\Everyday\GuideController;

use DB;
use  App\Http\Controllers\Api\v1\Astro\DataController;

/**
 * 每日运势
 */
class IndexController extends BaseController
{
    public $astro;
    // 行运数据
    public $transitsData = [];
    // 三限数据
    public $thirdprogressedData = [];

    public $thirdprogressedWholeData = [];
    // 天象数据
    public $nowData = [];
    // 本命数据
    public $natalData = [];

    public $natalWholeData = [];

    public $fiveIndex = [];

    public $isBirth = false;

    public $active = null;
    public $luckDisasters = null;

    public function index()
    {
        echo "index";
        exit;
    }


    /**
     * @param $rid
     * @param $time
     * @return array|\think\response\Json
     * @throws \app\common\lib\exception\ApiException
     */
    public function init($rid, $time)
    {
        $request = Request();
        $uid = $request->uid;

        $userinfo = (new Recode())->getRecode(['id' => $rid,'uid' => $uid]);

        $timeinfo = [
            'year'=>date('Y',$time),
            'month'=>date('m',$time),
            'day'=>date('d',$time),
            'hour'=>12,
            'minute'=>0,
        ];
        $timeinfo['timezone'] = 8;
        $timeinfo['is_summer'] = isSummerTime($timeinfo['hour'],$timeinfo['minute'],0, $timeinfo['month'],$timeinfo['day'],$timeinfo['year']) ? 1 : 0;

        if ($userinfo['month'] * 1 == $timeinfo['month'] * 1 && $userinfo['day'] * 1 == $timeinfo['day'] * 1) $this->isBirth = true;

        $this->astro = Astrolog::getInstance();
        $this->astro
            ->setRecode1($userinfo)
            ->setAdvance($timeinfo)
            ->setExecPrefix(config('astrolog.prefix'))
            ->setIsAstrolabe(false)
            ->setUserSetting(config('astroset.setting1'))
            ->setGetDatas(['now', 'natal', 'transits', 'thirdprogressed'])
            ->getAstroDatas();

        $this->nowData = $this->astro->getDatas('now');
        $this->natalData = $this->astro->getDatas('natal');
        $this->transitsData = $this->astro->getDatas('transits');
        $this->thirdprogressedData = $this->astro->getDatas('thirdprogressed');

        $this->astro->options['h_sys'] = 'w';
        $this->astro->setGetDatas(['natal', 'thirdprogressed'])->getAstroDatas();

        $this->natalWholeData = $this->astro->getDatas('natal');
        $this->thirdprogressedWholeData = $this->astro->getDatas('thirdprogressed');



        $active = $this->getActive();
        $luckDisasters = $this->getLuckDisasters();
        $this->active = $active;
        $this->luckDisasters = $luckDisasters;
        $ret['lucky_symbol'] = $this->getLuckySymbol($userinfo,$time);      // 获取幸运色等
//        $ret['fortune_list'] = $this->getActive();                          // 第一阶段 活跃
//        $ret['fortune_list'] = $this->getLuckDisasters();                   // 第二阶段 吉凶
        $ret['lucky_name'] = $this->getSuitable($userinfo,$time);           // 第三阶段 宜
        $ret['forbid_name'] = [];
        $avoid = $this->getAvoid();
        if(!empty($avoid))
        {
            foreach ($avoid as $avd)
            {
                // 宜中出现过的，忌中不显示
                if(!in_array($avd,$ret['lucky_name']))
                {
                    $ret['forbid_name'][] = $avd;
                }
            }
             if(empty($ret['forbid_name']))
            {
                $ret['forbid_name'][] = '百无禁忌';
            }

        }
//        $ret['forbid_name'] = $this->getAvoid();                            // 第四阶段 忌
        $ret['goddess_list'] = $this->getSaying($time);                     // 第五阶段 女神赠言
        $ret['revive_day'] = $this->getTopic($userinfo,$time);              // 第六阶段 某某之日 开心等五项指数
        $ret['fortune_advice'] = $this->getGuide();                         // 第七阶段 各项指南
        $ret['astro_tips'] = $this->getTips();                              // 第八阶段 每日运势小天象词条
        $ret['astro_name'] = '星象变动';
        $ret['astro_icon_url'] = config('fortune.astro');

        $fortune = $this->getFortuneScore();

        $ret['luck_adversity'] = $fortune['luck_adversity'];
        // 筛选需要显示的
        $ret['fortune_list'] = $fortune['fortune_list'];

        return $ret;
    }

    public function getFortuneScore()
    {
        $active = $this->active;
        $luckDisasters = $this->luckDisasters;

        $tp_planet = $this->thirdprogressedData['planets'];

        $colors = [
            0 => ['name' => '困难','color' => '#7775ff',],
            1 => ['name' => '警戒', 'color' => '#ffa536',],
            2 => ['name' => '平平', 'color' => '#ffed17',],
            3 => ['name' => '吉利', 'color' => '#00f4e7',],
            4 => ['name' => '大吉', 'color' => '#00e9a0',],
        ];

        $fortune_name = config('fortune.set');

        $result = [
            'fortune_list' => [],
            'luck_adversity' => $colors,
        ];

        $moon = $this->getScore();// 获取三限月亮吉凶 0=>吉  1=>凶
        $sun = $this->getScore(0);// 获取三限太阳吉凶 0=>吉  1=>凶
        $venu = $this->getScore(3);// 获取三限金星吉凶 0=>吉  1=>凶
        $merc = $this->getScore(2);// 获取三限水星吉凶 0=>吉  1=>凶

        $moon_good = ($moon['house']['good'] + $moon['planet']['good']) * 2;
        $moon_bad = ($moon['house']['bad'] + $moon['planet']['bad']);

        $score_good = $score_bad = 0;

        $score_good += ($moon_good + ($sun['house']['good'] + $sun['planet']['good'])/2
            + ($venu['house']['good'] + $venu['planet']['good'])/3
            + ($merc['house']['good'] + $merc['planet']['good'])/3);
        $score_bad += ($moon_bad + ($sun['house']['bad'] + $sun['planet']['bad'])/2
            + ($venu['house']['bad'] + $venu['planet']['bad'])/3
            + ($merc['house']['bad'] + $merc['planet']['bad'])/3);

        // 所有加减分叠加，得出三限整体吉分凶分，输出以下四条
        if(checkPhase([0],[ASC,MC],[0,180],$tp_planet))
        {
            $score_good += 3;
        }
        if(checkPhase([2],[ASC,MC],[0,180],$tp_planet))
        {
            $score_good += 2;
        }
        if(checkPhase([3],[ASC,MC],[0,180],$tp_planet))
        {
            $score_good += 10;
        }
        if(checkPhase([4],[ASC,MC],[0,180],$tp_planet))
        {
            $score_bad += 10;
        }
        if(checkPhase([6],[ASC,MC],[0,180],$tp_planet))
        {
            $score_bad += 10;
        }
        if(checkPhase([7],[ASC,MC],[0,180],$tp_planet))
        {
            $score_bad += 3;
        }
        if(checkPhase([8],[ASC,MC],[0,180],$tp_planet))
        {
            $score_bad += 10;
        }
        if(checkPhase([9],[ASC,MC],[0,180],$tp_planet))
        {
            $score_bad += 9;
        }

        $fortune_list = [];

        //三限月亮只有吉分且高于10 活跃分=吉分*2
        if($moon_good >= 10 && $moon_bad <= 0)
        {
            $score_mood_tp = $moon_good*2;
            $tp_status = 4;
        }
        //只有凶分且高于10 凶分*2
        elseif($moon_good <= 0 && $moon_bad >= 10)
        {
            $score_mood_tp = $moon_bad*2;
            $tp_status = 0;
        }
        //吉
        //  只有吉分且低于10
        //  只有宫位凶分星体为吉分
        //  吉大于凶分10以上
        //  活跃分= 吉分*2
        elseif(
            ($moon_good < 10 && $moon_good > 0 && $moon_bad <= 0)
            || ($moon['house']['good'] <= 0 && $moon['house']['bad'] > 0
                && $moon['planet']['good'] > 0 && $moon['planet']['bad'] <= 0)
            || ($moon_good - $moon_bad >= 10)
        )
        {
            $score_mood_tp = $moon_good*2;
            $tp_status = 3;
        }
        //凶
        //  只有凶分且低于10
        //      凶分*2
        //  只有宫位吉分星体为凶分
        //  凶大于吉分10以上
        elseif(
            ($moon_good <= 0 && $moon_bad > 0 && $moon_bad <= 10)
            || ($moon['house']['good'] > 0 && $moon['house']['bad'] <= 0
                && $moon['planet']['good'] <= 0 && $moon['planet']['bad'] > 0)
            || ($moon_bad - $moon_good >= 10)
        )
        {
            $score_mood_tp = $moon_bad*2;
            $tp_status = 1;
        }
        else
        {
            if($moon_good >= 15 && $moon_bad >= 15)
            {
                $score_mood_tp = 50;
            }
            else
            {
                $score_mood_tp = abs($moon_good - $moon_bad)*2;
            }
            $tp_status = 2;
        }

        if($score_mood_tp > 50) $score_mood_tp = 50;

        $mood_good_tr = $this->fiveIndex[2];
        $mood_bad_tr = $this->fiveIndex[3] + $this->fiveIndex[4];

        //行运只有吉分且高于10 活跃分=吉分*2
        if($mood_good_tr >= 10 && $mood_bad_tr <= 0)
        {
            $score_mood_tr = $mood_good_tr*2;
            $tr_status = 4;
        }
        //只有凶分且高于10 凶分*2
        elseif($mood_good_tr <= 0 && $mood_bad_tr >= 10)
        {
            $score_mood_tr = $mood_bad_tr*2;
            $tr_status = 0;
        }
        //吉
        //  只有吉分且低于10
        //  只有宫位凶分星体为吉分
        //  吉大于凶分10以上
        //  活跃分= 吉分*2
        elseif(
            ($mood_good_tr < 10 && $mood_good_tr > 0 && $mood_bad_tr <= 0)
            || ($mood_good_tr - $mood_bad_tr >= 10)
        )
        {
            $score_mood_tr = $mood_good_tr*2;
            $tr_status = 3;
        }
        //凶
        //  只有凶分且低于10
        //      凶分*2
        //  只有宫位吉分星体为凶分
        //  凶大于吉分10以上
        elseif(
            ($mood_good_tr <= 0 && $mood_bad_tr > 0 && $mood_bad_tr <= 10)
            || ($mood_bad_tr - $mood_good_tr >= 10)
        )
        {
            $score_mood_tr = $mood_bad_tr*2;
            $tr_status = 1;
        }
        else
        {
            if($mood_good_tr >= 15 && $mood_bad_tr >= 15)
            {
                $score_mood_tr = 50;
            }
            else
            {
                $score_mood_tr = abs($mood_good_tr - $mood_bad_tr)*2;
            }
            $tr_status = 2;
        }

        if($score_mood_tr > 50) $score_mood_tr = 50;

        if(
            ($tp_status == 4 && $tr_status == 4)
            || ($tp_status == 4 && $tr_status == 3)
            || ($tp_status == 3 && $tr_status == 4)
        )
        {
            $color_mood = $colors[4]['color'];
        }
        elseif(
            ($tp_status == 4 && $tr_status == 2)
            || ($tp_status == 3 && $tr_status == 3)
            || ($tp_status == 2 && $tr_status == 4)
            || ($tp_status == 2 && $tr_status == 3)
            || ($tp_status == 0 && $tr_status == 4)
        )
        {
            $color_mood = $colors[3]['color'];
        }
        elseif(
            ($tp_status == 4 && $tr_status == 1)
            || ($tp_status == 3 && $tr_status == 2)
            || ($tp_status == 2 && $tr_status == 2)
            || ($tp_status == 1 && $tr_status == 3)
            || ($tp_status == 0 && $tr_status == 4)
            || ($tp_status == 0 && $tr_status == 3)
        )
        {
            $color_mood = $colors[2]['color'];
        }
        elseif(
            ($tp_status == 4 && $tr_status == 0)
            || ($tp_status == 3 && $tr_status == 1)
            || ($tp_status == 3 && $tr_status == 0)
            || ($tp_status == 2 && $tr_status == 1)
            || ($tp_status == 1 && $tr_status == 2)
            || ($tp_status == 0 && $tr_status == 2)
        )
        {
            $color_mood = $colors[1]['color'];
        }
        else
        {
            $color_mood = $colors[0]['color'];
        }

        $score_mood = $score_mood_tp + $score_mood_tr;
        if($score_mood > 99) $score_mood = 99;
        elseif($score_mood < 1) $score_mood = 1;
        // 心情得分
        $fortune_list[8] = [
            'name' => $fortune_name[8],
            'score' => $score_mood,
            'color' => $color_mood,
        ];

        foreach ($luckDisasters as $k => $ld)
        {
            $temp_good = $ld['house']['good'];
            $temp_bad = $ld['house']['bad'];

            $score_status = 4;

            if(isset($ld['planet']))
            {
                $temp_good += $ld['planet']['good'];
                $temp_bad +=  $ld['planet']['bad'];
            }
            if($temp_bad >= 2)
            {
                if($temp_good >= 2)
                {
                    $score_status = 2;
                }
                elseif($temp_good >= 1)
                {
                    $score_status = 1;
                }
                else
                {
                    $score_status = 0;
                }
            }
            elseif($temp_bad >= 1)
            {
                if($temp_good >= 2)
                {
                    $score_status = 3;
                }
                elseif($temp_good >= 1)
                {
                    $score_status = 2;
                }
                else
                {
                    $score_status = 1;
                }
            }
            elseif($temp_bad < 1)
            {
                if($temp_good >= 2)
                {
                    $score_status = 4;
                }
                elseif($temp_good >= 1)
                {
                    $score_status = 3;
                }
                else
                {
                    $score_status = 2;
                }
            }



            if($k == 'money')
            {
                $key = 0;
                $name = $fortune_name[0];
            }
            elseif($k == 'work')
            {
                $key = 1;
                $name = $fortune_name[1];
            }
            elseif($k == 'study')
            {
                $key = 3;
                $name = $fortune_name[3];
            }
            elseif($k == 'love')
            {
                $key = 4;
                $name = $fortune_name[4];
            }
            elseif($k == 'talk')
            {
                $key = 5;
                $name = $fortune_name[5];
            }
            elseif($k == 'travel')
            {
                $key = 6;
                $name = $fortune_name[6];
            }
            elseif($k == 'family')
            {
                $key = 7;
                $name = $fortune_name[7];
            }
            else
            {
                //健康（先计算原来的健康值，并参考健康吉凶）
                //  大吉
                //      健康值/3
                //  吉
                //      健康值/2
                //  中
                //      健康值
                //  凶
                //      健康值*1.2
                //  大凶
                //      健康值*1.5
                $key = 2;
                $name = $fortune_name[2];
                if($score_status == 4) $active[$k] = $active[$k]/3;
                elseif($score_status == 3) $active[$k] = $active[$k]/2;
                elseif($score_status == 2) $active[$k] = $active[$k]/3;
                elseif($score_status == 1) $active[$k] = $active[$k]*1.2;
                elseif($score_status == 0) $active[$k] = $active[$k]*1.5;
            }
            //此时取三限月亮吉凶
            // 三限月亮大吉，所有项吉利上调一档
            // 三限月亮吉
            //  不明及其以下各档上调一档
            // 其它
            //  心情大凶
            //   所有项下调一档
            if($tp_status == 4)
            {
                $score_status++;
            }
            elseif($tp_status == 3 && $score_status <= 2)
            {
                $score_status++;
            }
            elseif($tp_status == 0)
            {
                $score_status--;
            }

            if($score_status > 4) $score_status = 4;
            if($score_status < 0) $score_status = 0;


            $active_score = $active[$k];
            if($active_score > 99) $active_score = 99;
            elseif($active_score < 1) $active_score = 1;

            $fortune_list[$key] = [
                'name' => $name,
                'score' => $active_score,
                'color' => $colors[$score_status]['color'],
            ];

        }
//        print_r($moon_good);
//        echo "\n";
//        print_r($moon_bad);
//        //（三限月亮吉分-凶分）*3=心情三限部分活跃分
//        $mood_tp = ($moon_good - $moon_bad) * 3;
//        // 心情行运部活跃分=（开心指数-愤怒指数-郁闷指数）*3
//        // $this->fiveIndex 0=>出行 1=>社交/桃花 2=>开心 3=>愤怒/意外 4=>郁闷
//        $mood_tr = ($this->fiveIndex[2] - $this->fiveIndex[3] - $this->fiveIndex[4]) * 3;

        $result['fortune_list'] = $fortune_list;

        return $result;
    }

    protected function getScore($p = 1)
    {
        $score_g = 0;
        $score_b = 0;
        $score_h_g = 0;
        $score_h_b = 0;
        $tp_planet = $this->thirdprogressedData['planets'];
        $tp_structure_t_square = $this->thirdprogressedData['structure']['t_square'];// 三限星体结构[T三角]数据

        if(!empty($tp_planet[$p]['phase']))
        {
            $phase_4689_num = 0;
            foreach ($tp_planet[$p]['phase'] as $phase)
            {
                if(in_array($phase['id'],[4,6,8,9])) $phase_4689_num++;
            }
            foreach ($tp_planet[$p]['phase'] as $phase)
            {
                if($phase['phase_e'] < 1)
                {
                    $phase_modulus = 1;
                }
                elseif($phase['phase_e'] < 2)
                {
                    $phase_modulus = 0.95;
                }
                elseif($phase['phase_e'] < 3)
                {
                    $phase_modulus = 0.9;
                }
                elseif($phase['phase_e'] < 4)
                {
                    $phase_modulus = 0.85;
                }
                elseif($phase['phase_e'] < 5)
                {
                    $phase_modulus = 0.8;
                }
                else
                {
                    $phase_modulus = 0.7;
                }

                // 火土海冥
                if(in_array($phase['id'],[4,6,8,9]))
                {
                    if(in_array($phase['phase_e'],[90,180]))
                    {
                        $score_b += 10;
                        if($tp_planet[$p]['in_house_id'] == 12 || $tp_planet[$phase['id']]['in_house_id'] == 12)
                        {
                            $score_b += 6;
                        }
                        if($tp_planet[$p]['in_house_id'] == 8 || $tp_planet[$phase['id']]['in_house_id'] == 8)
                        {
                            $score_b += 4;
                        }
                        if($tp_planet[$p]['in_house_id'] == 6 || $tp_planet[$phase['id']]['in_house_id'] == 6)
                        {
                            $score_b += 2;
                        }
                        if(is_in_t_square($tp_structure_t_square,1))
                        {
                            $score_b += 8;
                        }
                    }
                    elseif($phase['phase_e'] == 0)
                    {
                        $score_b += 5;
                        if($tp_planet[$p]['in_house_id'] == 12 || $tp_planet[$phase['id']]['in_house_id'] == 12)
                        {
                            $score_b += 4;
                        }
                        if($tp_planet[$p]['in_house_id'] == 8 || $tp_planet[$phase['id']]['in_house_id'] == 8)
                        {
                            $score_b += 3;
                        }
                        if($tp_planet[$p]['in_house_id'] == 6 || $tp_planet[$phase['id']]['in_house_id'] == 6)
                        {
                            $score_b += 2;
                        }
                        // TODO 月亮在火土海冥之间且同时合相，额外-5


                    }
                    elseif(in_array($phase['phase_e'],[60,120]))
                    {
                        $score_b += 3;
                        if($tp_planet[$p]['in_house_id'] == 12 || $tp_planet[$phase['id']]['in_house_id'] == 12)
                        {
                            $score_b += 4;
                        }
                        if($tp_planet[$p]['in_house_id'] == 8 || $tp_planet[$phase['id']]['in_house_id'] == 8)
                        {
                            $score_b += 3;
                        }
                        if($tp_planet[$p]['in_house_id'] == 6 || $tp_planet[$phase['id']]['in_house_id'] == 6)
                        {
                            $score_b += 2;
                        }
                        // 构成闭合三角且月亮仅与火土天海冥成相，额外-6
                        $is_in_trine = false;// 是否参与大三角
                        $is_in_small_triangle = false;// 是否参与小三角
                        $is_in_t_square = false;// 是否参与T三角
                        $is_in_bridge_triangle = false;// 是否参与桥三角
                        if(!empty($this->thirdprogressedData['structure']['trine']))
                        {
                            foreach ($this->thirdprogressedData['structure']['trine'] as $trine)
                            {
                                if(in_array($p,$trine)) $is_in_trine = true;
                            }
                        }
                        if(!empty($this->thirdprogressedData['structure']['small_triangle']))
                        {
                            foreach ($this->thirdprogressedData['structure']['small_triangle'] as $small_triangle)
                            {
                                if(in_array($p,$small_triangle)) $is_in_small_triangle = true;
                            }
                        }
                        if(!empty($this->thirdprogressedData['structure']['t_square']))
                        {
                            foreach ($this->thirdprogressedData['structure']['t_square'] as $t_square)
                            {
                                if(in_array($p,$t_square)) $is_in_t_square = true;
                            }
                        }
                        if(!empty($this->thirdprogressedData['structure']['bridge_triangle']))
                        {
                            foreach ($this->thirdprogressedData['structure']['bridge_triangle'] as $bridge_triangle)
                            {
                                if(in_array($p,$bridge_triangle)) $is_in_bridge_triangle = true;
                            }
                        }
                        if(checkPhase([$p],[4,6,7,8,9],[],$tp_planet) && !checkPhase([$p],[0,1,2,3,5],[],$tp_planet)
                            && ($is_in_trine || $is_in_small_triangle || $is_in_t_square || $is_in_bridge_triangle))
                        {
                            $score_b += 6;
                        }
                    }
                }
                // 天王
                elseif($phase['id'] == 7)
                {
                    if(in_array($phase['phase_e'],[90,180]))
                    {
                        $score_b += 5;
                        if($tp_planet[$p]['in_house_id'] == 12 || $tp_planet[$phase['id']]['in_house_id'] == 12)
                        {
                            $score_b += 4;
                        }
                        if($tp_planet[$p]['in_house_id'] == 8 || $tp_planet[$phase['id']]['in_house_id'] == 8)
                        {
                            $score_b += 3;
                        }
                        if($tp_planet[$p]['in_house_id'] == 6 || $tp_planet[$phase['id']]['in_house_id'] == 6)
                        {
                            $score_b += 2;
                        }
                        // 若同时有火土海冥刑冲或同时与火土海冥之二成相，额外-4
                        if(checkPhase([$p],[4,6,8,9],[90,180],$tp_planet) || $phase_4689_num >= 2)
                        {
                            $score_b += 4;
                        }
                        // 若星盘上有日或金或水参与的T三角（火土冥海必参与一个），则额外-5
                        if((is_in_t_square($tp_structure_t_square,0)
                            || is_in_t_square($tp_structure_t_square,2)
                            || is_in_t_square($tp_structure_t_square,3))
                            && (is_in_t_square($tp_structure_t_square,4)
                                || is_in_t_square($tp_structure_t_square,6)
                                || is_in_t_square($tp_structure_t_square,8)
                                || is_in_t_square($tp_structure_t_square,9)
                            )
                        )
                        {
                            $score_b += 5;
                        }
                    }
                    elseif($phase['phase_e'] == 0)
                    {
                        $score_b += 1;
                        // 若同时有火土海冥刑冲或同时与火土海冥之二成相，额外-3
                        if(checkPhase([$p],[4,6,8,9],[90,180],$tp_planet) || $phase_4689_num >= 2)
                        {
                            $score_b += 3;
                        }
                        // 若同时与金木之一成相，额外+5
                        if(checkPhase([$p],[3,5],[],$tp_planet))
                        {
                            $score_g += 5;
                        }
                    }
                    elseif(in_array($phase['phase_e'],[60,120]))
                    {
                        // 若同时有火土海冥刑冲或同时与火土海冥之二成相，额外-2
                        if(checkPhase([$p],[4,6,8,9],[90,180],$tp_planet) || $phase_4689_num >= 2)
                        {
                            $score_b += 2;
                        }
                        // 若同时与金木之一成相或天王与金木之一成合拱六分，额外+4
                        if(checkPhase([$p],[3,5],[],$tp_planet)
                            || checkPhase([7],[3,5],[0,60,120],$tp_planet))
                        {
                            $score_g += 4;
                        }
                    }
                }
                // 金木
                elseif(in_array($phase['id'],[3,5]))
                {
                    if($phase['phase_e'] == 0) $score_g += 10;
                    elseif(in_array($phase['phase_e'],[60,120])) $score_g += 7;
                    elseif($phase['phase_e'] == 180) $score_g += 7;
                    elseif($phase['phase_e'] == 90)
                    {
                        $score_g += 3;
                        $score_b += 3;
                    }
                    if(in_array($tp_planet[$p]['in_house_id'],[5,11]))
                    {
                        $score_g += 3;
                    }
                    elseif(in_array($tp_planet[$p]['in_house_id'],[1,4,7,10]))
                    {
                        $score_g += 2;
                    }
                }
                // 日水
                elseif(in_array($phase['id'],[0,2]))
                {
                    if(in_array($phase['phase_e'],[60,120]))
                    {
                        $score_g += 2;
                    }
                    elseif($phase['phase_e'] == 180)
                    {
                        $score_b += 1;
                        if($tp_planet[$p]['in_house_id'] == 12 || $tp_planet[$phase['id']]['in_house_id'] == 12)
                        {
                            $score_b += 4;
                        }
                        if($tp_planet[$p]['in_house_id'] == 8 || $tp_planet[$phase['id']]['in_house_id'] == 8)
                        {
                            $score_b += 3;
                        }
                        if($tp_planet[$p]['in_house_id'] == 6 || $tp_planet[$phase['id']]['in_house_id'] == 6)
                        {
                            $score_b += 2;
                        }
                    }
                    elseif($phase['phase_e'] == 90)
                    {
                        $score_b += 3;
                        if($tp_planet[$p]['in_house_id'] == 12 || $tp_planet[$phase['id']]['in_house_id'] == 12)
                        {
                            $score_b += 4;
                        }
                        if($tp_planet[$p]['in_house_id'] == 8 || $tp_planet[$phase['id']]['in_house_id'] == 8)
                        {
                            $score_b += 3;
                        }
                        if($tp_planet[$p]['in_house_id'] == 6 || $tp_planet[$phase['id']]['in_house_id'] == 6)
                        {
                            $score_b += 2;
                        }
                    }
                }
                $score_g *= $phase_modulus;
                $score_b *= $phase_modulus;
            }
        }

        if($tp_planet[$p]['in_house_id'] == 1) $score_h_g += 6;
        elseif($tp_planet[$p]['in_house_id'] == 2) $score_h_g += 1;
        elseif($tp_planet[$p]['in_house_id'] == 3) $score_h_g += 3;
        elseif($tp_planet[$p]['in_house_id'] == 4) $score_h_g += 5;
        elseif($tp_planet[$p]['in_house_id'] == 5) $score_h_g += 10;
        elseif($tp_planet[$p]['in_house_id'] == 6) $score_h_b += 3;
        elseif($tp_planet[$p]['in_house_id'] == 7) $score_h_g += 6;
        elseif($tp_planet[$p]['in_house_id'] == 8) $score_h_b += 5;
        elseif($tp_planet[$p]['in_house_id'] == 9) $score_h_g += 7;
        elseif($tp_planet[$p]['in_house_id'] == 10) $score_h_g += 6;
        elseif($tp_planet[$p]['in_house_id'] == 11) $score_h_g += 7;
        elseif($tp_planet[$p]['in_house_id'] == 12) $score_h_b += 7;

        $result = [
            'house'=>[
                'good' => $score_h_g,
                'bad' => $score_h_b,
            ],
            'planet'=>[
                'good' => $score_g,
                'bad' => $score_b,
            ],
        ];

        return $result;
    }

    /**
     * 获取幸运色、幸运星座、幸运方位、幸运数
     * @param array $userinfo
     * @param int $time
     * @return array
     */
    protected function getLuckySymbol(array $userinfo,int $time)
    {
        $luckything = new LuckythingController();

        // 先计算出行运盘和三限盘的数据
        $luckything->transitsData = $this->transitsData;
        $luckything->thirdprogressedData = $this->thirdprogressedData;
        $luckything->natalData = $this->natalData;
        $luckything->nowData = $this->nowData;
        $luckything->userinfo = $userinfo;
        $luckything->now_time = $time;
        $data = $luckything->init();
        return $data;
    }
    /**
     * 获取每日运势活跃分数
     * @return array
     */
    public function getActive()
    {
        $active = new Active_devController();

        // 先计算出行运盘和三限盘的数据
        $active->transitsData = $this->transitsData;
        $active->thirdprogressedData = $this->thirdprogressedData;
        $active->natalData = $this->natalData;
        $data = $active->init();

        return $data;
    }
    /**
     * 获取每日运势吉凶
     * @return array
     */
    protected function getLuckDisasters()
    {
        $luckdisasters = new LuckdisastersController();

        // 先计算出行运盘和三限盘的数据
        $luckdisasters->transitsData = $this->transitsData;
        $luckdisasters->thirdprogressedData = $this->thirdprogressedData;
        $data = $luckdisasters->init();

        return $data;
    }
    /**
     * 获取每日宜忌-宜
     * @param array $userinfo
     * @param int $time
     * @param bool $index
     * @return array
     */
    public function getSuitable(array $userinfo,int $time,$index = false)
    {
        $suitable = new SuitableController();
        $birthtime = strtotime($userinfo['year'].'-'.$userinfo['month'].'-'.$userinfo['day'].' '.$userinfo['hour'].':'.$userinfo['minute']);

        $timeinfo = [
            'year'=>date('Y',$time),
            'month'=>date('m',$time),
            'day'=>date('d',$time),
            'hour'=>date('H',$time),
            'minute'=>date('i',$time),
        ];
        $timeinfo['timezone'] = 8;
        $timeinfo['is_summer'] = isSummerTime($timeinfo['hour'],$timeinfo['minute'],0,
            $timeinfo['month'],$timeinfo['day'],$timeinfo['year']) ? 1 : 0;

        // 先计算出行运盘和三限盘的数据
        $suitable->transitsData = $this->transitsData;
        $suitable->thirdprogressedData = $this->thirdprogressedData;
        $suitable->natalData = $this->natalData;
        $suitable->nowData = $this->nowData;
        $suitable->time = $time;
        $suitable->birthtime = $birthtime;
        $suitable->sunDeg = $this->getNewMoonData($timeinfo);// 新月度数

        $data = $suitable->init($index);

        return $data;
    }
    /**
     * 获取每日宜忌-忌
     * @param bool $index
     * @return array
     */
    public function getAvoid($index = false)
    {
        $avoid = new AvoidController();
        // 先计算出行运盘和三限盘的数据
        $avoid->transitsData = $this->transitsData;
        $avoid->thirdprogressedData = $this->thirdprogressedData;
        $avoid->natalData = $this->natalData;
        $avoid->nowData = $this->nowData;
        $data = $avoid->init($index);
        if(empty($data)) $data[] = '百无禁忌';
        return $data;
    }

    /**
     * 获取女神赠言
     * @param int $time
     * @return array
     */
    protected function getSaying(int $time)
    {
        $saying = new SayingController();

        $timeinfo = [
            'year'=>date('Y',$time),
            'month'=>date('m',$time),
            'day'=>date('d',$time),
            'hour'=>date('H',$time),
            'minute'=>date('i',$time),
        ];
        $timeinfo['timezone'] = intval(request()->input('timezone')) ?? 8;
        $timeinfo['is_summer'] = isSummerTime($timeinfo['hour'],$timeinfo['minute'],0,
            $timeinfo['month'],$timeinfo['day'],$timeinfo['year']) ? 1 : 0;

        // 先计算出行运盘和三限盘的数据
        $saying->transitsData = $this->transitsData;
        $saying->thirdprogressedData = $this->thirdprogressedData;
        $saying->natalData = $this->natalData;
        $saying->nowData = $this->nowData;
        $data = $saying->init();

        return $data;
    }

    /**
     * 获取某某之日
     * @param array $userinfo
     * @param int $time
     * @param bool $index
     * @return array
     * @throws ApiException
     */
    public function getTopic(array $userinfo,int $time,$index = false)
    {
        $topic = new TopicController();

        $timeinfo = [
            'year'=>date('Y',$time),
            'month'=>date('m',$time),
            'day'=>date('d',$time),
            'hour'=>date('H',$time),
            'minute'=>date('i',$time),
        ];
        $timeinfo['timezone'] = 8;
        $timeinfo['is_summer'] = isSummerTime($timeinfo['hour'],$timeinfo['minute'],0,
            $timeinfo['month'],$timeinfo['day'],$timeinfo['year']) ? 1 : 0;

        $topic->transitsData = $this->transitsData;
        $topic->thirdprogressedData = $this->thirdprogressedData;
        $topic->natalData = $this->natalData;
        $topic->nowData = $this->nowData;
        $topic->recode = $userinfo;
        $topic->advance = $timeinfo;
        $topic->year = $timeinfo['year'];
        $topic->sex = $userinfo['type'];
        $topic->isBirth = $this->isBirth;// 生日显示为欢庆之日
        $topic->sunDeg = $this->getNewMoonData($timeinfo);// 新月度数

        $timestamp0 = getEclipse($time,$timeinfo['timezone'],0);// 日食时间
        $timestamp1 = getEclipse($time,$timeinfo['timezone'],1);// 月食时间

        if(date('Y-m-d',$timestamp0) === date('Y-m-d',$time))
        {
            $topic->solarEclipse = $timestamp0;
            $time0info = [
                'year'=>date('Y',$timestamp0),
                'month'=>date('m',$timestamp0),
                'day'=>date('d',$timestamp0),
                'hour'=>date('H',$timestamp0),
                'minute'=>date('i',$timestamp0),
            ];
            $time0info['timezone'] = 8;
            $time0info['is_summer'] = isSummerTime($timeinfo['hour'],$timeinfo['minute'],0,
                $timeinfo['month'],$timeinfo['day'],$timeinfo['year']);

           /* $this->astro->options['advance'] = $time0info;
            $this->astro->getAstroDatas();
            $sources = $this->astro->datas;
            $topic->solarTransitsData = $sources['transits_data'];*/
//          $topic->solarTransitsData = $this->getTransitsData($userinfo,$time0info);
            $topic->solarTransitsData = $this->astro->setAdvance($time0info)->setGetDatas(['transits'])->getAstroDatas()->getDatas('transits');
        }
        else
        {
            $topic->solarEclipse = false;
            $topic->solarTransitsData = [];
        }
        if(date('Y-m-d',$timestamp1) == date('Y-m-d',$time))
        {
            $topic->lunarEclipse = $timestamp1;
            $time1info = [
                'year'=>date('Y',$timestamp1),
                'month'=>date('m',$timestamp1),
                'day'=>date('d',$timestamp1),
                'hour'=>date('H',$timestamp1),
                'minute'=>date('i',$timestamp1),
            ];
            $time1info['timezone'] = 8;
            $time1info['is_summer'] = isSummerTime($timeinfo['hour'],$timeinfo['minute'],0,
            $timeinfo['month'],$timeinfo['day'],$timeinfo['year']);
            $topic->lunarTransitsData = $this->astro->setAdvance($time1info)->setGetDatas(['transits'])->getAstroDatas()->getDatas('transits');
            /*$this->astro->options['advance'] = $time1info;
            $this->astro->getAstroDatas();
            $sources = $this->astro->datas;
            $topic->lunarTransitsData = $sources['transits_data'];*/
//            $topic->lunarTransitsData = $this->getTransitsData($userinfo,$time1info);
        }
        else
        {
            $topic->lunarEclipse = false;
            $topic->lunarTransitsData = [];
        }

        $topic->active = $this->active;
        $topic->luckDisasters = $this->luckDisasters;

        $data = $topic->init($index);

        $this->fiveIndex = $topic->fiveIndex;

        return $data;
    }
    /**
     * 获取各项指南
     * @return array
     */
    protected function getGuide()
    {
        $guide = new GuideController();

        $guide->transitsData = $this->transitsData;
        $guide->thirdprogressedData = $this->thirdprogressedData;
        $guide->thirdprogressedWholeData = $this->thirdprogressedWholeData;
        $guide->natalData = $this->natalData;
        $guide->natalWholeData = $this->natalWholeData;
        $guide->nowData = $this->nowData;
        $data = $guide->init();

        return $data;
    }
    /**
     * 获取每日运势-小天象词条
     * @return array
     */
    protected function getTips()
    {
        $tips = new TipsController();

        $tips->transitsData = $this->transitsData;
        $tips->nowData = $this->nowData;
        $data = $tips->init();

        return $data;
    }

//    /**
//     * 获取行运盘数据
//     * @param array $userinfo 用户档案信息
//     * @param array $timeinfo 当前时间信息
//     * @return array
//     * @throws ApiException
//     */
//    public function getTransitsData(array $userinfo,array $timeinfo)
//    {
//        $Data = new DataController();
//
//        $timestamp1 = $Data->deal_time($userinfo);
//        $utdatenow1 = strftime("%d.%m.%Y", $timestamp1);
//        $utnow1 = strftime("%H:%M:%S", $timestamp1);
//        $longitude1 = ($userinfo['long_deg'] + $userinfo['long_min'] / 60 ) * $userinfo['ew'];
//        $latitude1 = ($userinfo['lat_deg'] + $userinfo['lat_min'] / 60 ) * $userinfo['ns'];
//
//        $timestamp2 = $Data->deal_time($timeinfo);
//        $utdatenow2 = strftime("%d.%m.%Y", $timestamp2);
//        $utnow2 = strftime("%H:%M:%S", $timestamp2);
//        $longitude2 = number_format(floatval(request()->input('longitude')),8);
//        $latitude2 = number_format(floatval(request()->input('latitude')),8);
//
//        $h_sys = 'p';
//        $Data->planets_display = '111111111100000001001';
//        $Data->asps_display = [0,60,90,120,180];
//        $Data->asp_orb_all = [0=>2,60=>1,90=>2,120=>2,180=>2,30=>1,150=>2,45=>2,135=>2,72=>2,144=>2];
//        $Data->planet_orb_all = [0,0,0,0,0,0,0,0,0,0];// 月亮容许度暂时去掉 5
//        $exec_str1 = config('astrolog.prefix')." -b{$utdatenow1} -ut{$utnow1} -p0123456789DAmHt -eswe -house{$longitude1},{$latitude1},{$h_sys} -flds -g, -head";
//        $exec_str2 = config('astrolog.prefix')." -b{$utdatenow2} -ut{$utnow2} -p0123456789DAmHt -eswe -house{$longitude1},{$latitude1},{$h_sys} -flds -g, -head";
//
//        exec ($exec_str1, $out1);
//        exec ($exec_str2, $out2);
//        $original_data1 = $Data->getOriginalData($out1,$h_sys);
//        $original_data2 = $Data->getOriginalData($out2,$h_sys);
//        $Data->array_remove($original_data1,$Data->planets_display);
//        $Data->array_remove($original_data2,$Data->planets_display);
//
//        $details1 = $Data->getPlanetHouseDetail($original_data1, $original_data1['hc1']);
//        $phase1 = $Data->planetPkPlanet($original_data1, $original_data2, false,1);
//        foreach ($phase1['planets'] as $k1 => $d1)
//        {
//            $details1['planets'][$k1]['phase'] = $d1['phase'];
//            if(empty($d1['phase'])) $details1['planets'][$k1]['phase'] = null;
//        }
//        $details1['phase'] = $phase1['phase'];
//        $details2 = $Data->getPlanetHouseDetail($original_data2, $original_data1['hc1']);
//        $phase2 = $Data->planetPkPlanet($original_data2, $original_data1, false,2);
//        foreach ($phase2['planets'] as $k2 => $d2)
//        {
//            $details2['planets'][$k2]['phase'] = $d2['phase'];
//            if(empty($d2['phase'])) $details2['planets'][$k2]['phase'] = null;
//        }
//        $details2['phase'] = $phase2['phase'];
//
//        return [$details1,$details2];
//    }
//
//    /**
//     * 获取本命盘数据-普宫
//     * @param array $userinfo 用户档案信息
//     * @param string $h_sys 分宫制 默认  整宫制
//     * @return array
//     * @throws ApiException
//     */
//    public function getNatalData(array $userinfo,$h_sys='p')
//    {
//        $Data = new DataController();
//
//        $timestamp1 = $Data->deal_time($userinfo);
//
//        $utdatenow = strftime("%d.%m.%Y", $timestamp1);
//        $utnow = strftime("%H:%M:%S", $timestamp1);
//
//        $longitude = ($userinfo['long_deg'] + $userinfo['long_min'] / 60 ) * $userinfo['ew'];
//        $latitude = ($userinfo['lat_deg'] + $userinfo['lat_min'] / 60 ) * $userinfo['ns'];
//
//        $Data->planets_display = '111111111100100001001';
//        $Data->asps_display = [0,60,90,120,180];
//        $Data->asp_orb_all = [0=>8,60=>6,90=>7,120=>7,180=>7,30=>1,150=>2,45=>2,135=>2,72=>2,144=>2];
//        $Data->planet_orb_all = [0,0,0,0,0,0,0,0,0,0];
//
//        $exec_str = config('astrolog.prefix')." -b{$utdatenow} -ut{$utnow} -p0123456789DAmHt -eswe -house{$longitude},{$latitude},{$h_sys} -flds -g, -head";
//
//        exec ($exec_str, $out);
//        $original_data = $Data->getOriginalData($out,$h_sys);
//        $Data->array_remove($original_data,$Data->planets_display);
//        $details = $Data->getPlanetHouseDetail($original_data, $original_data['hc1'],$userinfo['year']);
//
//        $phase = $Data->planetPkPlanet($original_data, $original_data, true);
//        foreach ($phase['planets'] as $k => $d)
//        {
//            $details['planets'][$k]['phase'] = $d['phase'];
//            if(empty($d['phase'])) $details['planets'][$k]['phase'] = null;
//        }
//
//        $details['phase'] = $phase['phase'];
//
//        return $details;
//    }
//
//    /**
//     * 获取天象盘数据-普宫
//     * @param array $timeinfo
//     * @param string $h_sys 分宫制
//     * @return array
//     * @throws ApiException
//     */
//    public function getNowData(array $timeinfo,$h_sys='p')
//    {
//        $Data = new DataController();
//
//        $timestamp = $Data->deal_time($timeinfo);
//        $utdatenow = strftime("%d.%m.%Y", $timestamp);
//        $utnow = strftime("%H:%M:%S", $timestamp);
//        $longitude = number_format(floatval(request()->input('longitude')),8);
//        $latitude = number_format(floatval(request()->input('latitude')),8);
//
//        $Data->planets_display = '111111111100100001001';
//        $Data->asps_display = [0,60,90,120,180];
//        $Data->asp_orb_all = [0=>8,60=>6,90=>7,120=>7,180=>7,30=>1,150=>2,45=>2,135=>2,72=>2,144=>2];
//        $Data->planet_orb_all = [0,0,0,0,0,0,0,0,0,0];
//
//        $exec_str = config('astrolog.prefix')." -b{$utdatenow} -ut{$utnow} -p0123456789DAmHt -eswe -house{$longitude},{$latitude},{$h_sys} -flds -g, -head";
//
//        exec ($exec_str, $out);
//        $original_data = $Data->getOriginalData($out,$h_sys);
//        $Data->array_remove($original_data,$Data->planets_display);
//        $details = $Data->getPlanetHouseDetail($original_data, $original_data['hc1'],$timeinfo['year']);
//
//        $phase = $Data->planetPkPlanet($original_data, $original_data, true);
//        foreach ($phase['planets'] as $k => $d)
//        {
//            $details['planets'][$k]['phase'] = $d['phase'];
//            if(empty($d['phase'])) $details['planets'][$k]['phase'] = null;
//        }
//
//        $details['phase'] = $phase['phase'];
//
//        $details = $this->get_structure($details);
//
//        return $details;
//    }
//
//    /**
//     * 获取三限盘数据-普宫
//     * @param array $userinfo 用户档案信息
//     * @param array $timeinfo 当前时间信息
//     * @param string $h_sys 分宫制
//     * @return array
//     * @throws ApiException
//     */
//    public function getThirdprogressedData(array $userinfo,array $timeinfo,string $h_sys = 'p')
//    {
//        $Data = new DataController();
//
//        $Data->planets_display = '111111111100000001001';
//        $Data->asps_display = [0,60,90,120,180];
//        $Data->asp_orb_all = [0=>8,60=>6,90=>7,120=>7,180=>7,30=>1,150=>2,45=>2,135=>2,72=>2,144=>2];
//        $Data->planet_orb_all = [0,0,0,0,0,0,0,0,0,0];
//
//        $timeinfo['timezone'] = intval(request()->input('timezone'));
//        $timeinfo['is_summer'] = isSummerTime($timeinfo['hour'],$timeinfo['minute'],0,
//            $timeinfo['month'],$timeinfo['day'],$timeinfo['year']) ? 1 : 0;
//
//        $timestamp1 = $Data->deal_time($userinfo);
//
//        $utdatenow = strftime("%d.%m.%Y", $timestamp1);
//        $utnow = strftime("%H:%M:%S", $timestamp1);
//
//        $longitude = ($userinfo['long_deg'] + $userinfo['long_min'] / 60 ) * $userinfo['ew'];
//        $latitude = ($userinfo['lat_deg'] + $userinfo['lat_min'] / 60 ) * $userinfo['ns'];
//
//        $exec_str  = config('astrolog.prefix')." -b{$utdatenow} -ut{$utnow} -p0 -eswe -house{$longitude},{$latitude},{$h_sys} -fj -g, -head";
//        exec ($exec_str, $out);
//
//        $timestamp2 = $Data->deal_time($timeinfo);
//
//        $birth_JD = gregoriantojd(date('m',$timestamp1), date('d',$timestamp1), date('Y',$timestamp1)) + ((date('H',$timestamp1) + (date('i',$timestamp1) / 60)) / 24);
//        $start_JD = gregoriantojd(date('m',$timestamp2), date('d',$timestamp2), date('Y',$timestamp2)) + ((date('H',$timestamp2) + (date('i',$timestamp2) / 60)) / 24);
//        $days_alive = $start_JD - $birth_JD; // 总天数
//        $prog_time_to_add = $days_alive / 27.321661; // 多少月  即本命后第几天27.321661     27.3215865
//
//        // 夜间盘
//        if($out[0] > 0 || $out[0] < 7)
//        {
//            $time_before_JD=$birth_JD+floor($prog_time_to_add);
//        }
//        else
//        {
//            $time_before_JD=$birth_JD+floor($prog_time_to_add);
//        }
//
//
//        //变化比率 //就是$prog_time_to_add的去掉整数的小数
//        $time_change_pro=$prog_time_to_add-floor($prog_time_to_add);
//
//        $date_before = strtotime(jdtogregorian($time_before_JD));
//        $date_after = strtotime('+1 day',$date_before);
//
//        $utdatenow1 = strftime("%d.%m.%Y", $date_before);
//        $utnow1 = strftime("%H:%M:%S", $timestamp1);
//
//
//        $utdatenow2 = strftime("%d.%m.%Y", $date_after);
//        $utnow2 = strftime("%H:%M:%S", $timestamp1);
//
//
//
//        $exec_str1 = config('astrolog.prefix')." -b{$utdatenow1} -ut{$utnow1} -p0123456789DAmHt -eswe -house{$longitude},{$latitude},{$h_sys} -flds -g, -head";
//        $exec_str2 = config('astrolog.prefix')." -b{$utdatenow2} -ut{$utnow2} -p0123456789DAmHt -eswe -house{$longitude},{$latitude},{$h_sys} -flds -g, -head";
//
//        exec ($exec_str1, $out1);
//        exec ($exec_str2, $out2);
//        $calOut = $Data->getProgressionThirdprogressed($out1,$out2,$time_change_pro);
//
//        $original_data = $Data->getOriginalData($calOut,$h_sys);
//        $Data->array_remove($original_data,$Data->planets_display);
//
//        $details = $Data->getPlanetHouseDetail($original_data, $original_data['hc1']);
//        $phase = $Data->planetPkPlanet($original_data, $original_data, true);
//        foreach ($phase['planets'] as $k => $d)
//        {
//            $details['planets'][$k]['phase'] = $d['phase'];
//            if(empty($d['phase'])) $details['planets'][$k]['phase'] = null;
//        }
//        $details['phase'] = $phase['phase'];
//
//        $details['time1'] = date('Y-m-d H:i:s',$date_before);
//
//        $details = $this->get_structure($details);
//
//        return $details;
//    }
//    /**
//     * 获取行星结构
//     * 大三角
//     * 120°-120°-120°
//     * 小三角 与两颗星都成60度的这颗星称为顶星
//     * 120°-60°-60°
//     * T三角 与两星成90度的星体称为“T顶点”
//     * 180°-90°-90°
//     * 桥三角：两颗星180度，同时有第三颗星与两星分别成60度和120度。该星称为桥星。
//     * 180°-60°-120°
//     * 大十字：四颗星组成一个正四方形，每颗星都与另外两颗成90度（可以认为是在T三角基础上，加上一颗与T顶点对冲的行星）
//     * 180°-90°-90°-180°
//     * 大信封：桥三角的桥星对面多出一颗对冲的行星
//     * 大风筝：大三角顶星的对面，多出一颗与它成180度的行星
//     */
//    protected function get_structure($base_data = [])
//    {
//        $ret = [
//            'trine'=>[],
//            'small_triangle'=>[],
//            't_square'=>[],
//            'bridge_triangle'=>[],
//        ];
//        for($i = 0; $i < 10; $i ++)
//        {
//            $a = $base_data['planets'][$i];
//            $phasei = $a['phase'];
//            for($j = 0; $j < 10; $j ++)
//            {
//                $b = $base_data['planets'][$j];
//                $phasej = $b['phase'];
//                // 大三角 + 小三角
//                if (isset($phasei[$i . "-" . $j]) && $phasei[$i . "-" . $j]['phase_e'] == 120 && $i < $j)
//                {
//                    for($z = 0; $z < 10; $z ++)
//                    {
//                        $c = $base_data['planets'][$z];
//                        // 大三角
//                        if (isset($phasei[$i . "-" . $z]) && $phasei[$i . "-" . $z]['phase_e'] == 120 && $j < $z
//                            && isset($phasej[$j . "-" . $z]) && $phasej[$j . "-" . $z]['phase_e'] == 120 )
//                        {
//                            $ret['trine'][] = [$i,$j,$z];
//                            for ($y=0; $y < 10;$y++)
//                            {
//                                $d = $base_data['planets'][$y];
//                                $phasey = $d['phase'];
//                                // 大风筝：大三角顶星的对面，多出一颗与它成180度的行星
//                                if (isset($phasey[$y . "-" . $z]) && $phasey[$y . "-" . $z]['phase_e'] == 180)
//                                {
//                                    $ret['kite'][] = [$i,$j,$z,$y];
//                                }
//                            }
//                        }
//                        // 小三角
//                        elseif(isset($phasei[$i . "-" . $z]) && $phasei[$i . "-" . $z]['phase_e'] == 60 && $j < $z
//                            && isset($phasej[$j . "-" . $z]) && $phasej[$j . "-" . $z]['phase_e'] == 60 )
//                        {
//                            $ret['small_triangle'][] = [$i,$j,$z];
//                        }
//                    }
//                }
//                // T三角
//                elseif(isset($phasei[$i . "-" . $j]) && $phasei[$i . "-" . $j]['phase_e'] == 180 && $i < $j )
//                {
//                    for($z = 0; $z < 10; $z ++) {
//                        $c = $base_data['planets'][$z];
//                        $phasez = $c['phase'];
//                        // T三角
//                        if (isset($phasei[$i . "-" . $z]) && $phasei[$i . "-" . $z]['phase_e'] == 90 && $i != $z
//                            && isset($phasej[$j . "-" . $z]) && $phasej[$j . "-" . $z]['phase_e'] == 90 && $j != $z
//                        ) {
//                            $ret['t_square'][] = [$i,$j,$z];
//                            for ($y=0; $y < 10;$y++)
//                            {
//                                $d = $base_data['planets'][$y];
//                                $phasey = $d['phase'];
//
//                                // 大十字
//                                if(isset($phasey[$y . "-" . $z]) && $phasey[$y . "-" . $z]['phase_e'] == 180 && $i < $z
//                                    && isset($phasey[$y . "-" . $j]) && $phasey[$y . "-" . $j]['phase_e'] == 90
//                                    && isset($phasey[$y . "-" . $i]) && $phasey[$y . "-" . $i]['phase_e'] == 90 && $z < $y
//                                )
//                                {
//                                    $ret['cross'][] = [$i,$j,$z,$y];
//                                }
//                            }
//                        }
//                        // 桥三角 两颗星180度，同时有第三颗星与两星分别成60度和120度。该星称为桥星。
//                        // 大信封：桥三角的桥星对面多出一颗对冲的行星
//                        elseif ($i != $z && $j != $z &&
//                            ((isset($phasez[$z . "-" . $i]) && $phasez[$z . "-" . $i]['phase_e'] == 120
//                                    && isset($phasez[$z . "-" . $j]) && $phasez[$z . "-" . $j]['phase_e'] == 60)
//                                || (isset($phasez[$z . "-" . $i]) && $phasez[$z . "-" . $i]['phase_e'] == 60
//                                    && isset($phasez[$z . "-" . $j]) && $phasez[$z . "-" . $j]['phase_e'] == 120))
//                        )
//                        {
//                            $ret['bridge_triangle'][] = [$i,$j,$z];
//                            for ($y=0;$y<10;$y++)
//                            {
//                                $d = $base_data['planets'][$y];
//                                $phasey = $d['phase'];
//                                // 大信封
//                                if (isset($phasey[$y . "-" . $z]) && $phasey[$y . "-" . $z]['phase_e'] == 180
//                                    && $z < $y && $i< $z
//                                )
//                                {
//                                    $ret['envelop'][] = [$i,$j,$z,$y];
//                                }
//                            }
//                        }
//                    }
//                }
//            }
//        }
//
//        $base_data['structure'] = $ret;
//
//        return $base_data;
//    }
    /**
     * 获取新月度数 若无返回-1
     * @param array $timeinfo
     * @param int $deg 日月成相度数 待封装满月时使用
     * @return float
     * @throws ApiException
     */
    protected function getNewMoonData(array $timeinfo,$deg = 0)
    {
        $result = -1;

//        $Data = new Data();
        $timestamp = (new Astrolog())->dealtime($timeinfo);
        $timestamp -= ($timeinfo['timezone'] + 12) * 3600;
        $utdatenow = strftime("%d.%m.%Y", $timestamp);
        $utnow = strftime("%H:%M:%S", $timestamp);

        // 按照速度计算具体新月时间和度数  有误差
//        $exec_str = config('astrolog.prefix')." -b{$utdatenow} -p01 -eswe -fls -g,  -head -n1 -s1d";
//        unset($out);
//        exec ($exec_str, $out);
//
//        $sun = explode(',',$out[0]);
//        $moon = explode(',',$out[1]);
//
//        $speed_diff = $moon[1] * 1 - $sun[1] * 1;// 速度差值
//        $sun_deg = $sun[0] * 1;
//        $moon_deg = $moon[0] * 1;
//
//        // 是否可能存在精准合相
//        // 太阳53度，速度0.9  月亮46度，速度13；
//        if(($sun_deg > $moon_deg && $sun_deg - $moon_deg <= $speed_diff))
//        {
//            $change = ceil(($sun_deg - $moon_deg) / $speed_diff * 24 * 60);//分钟数
//            $timestamp = strtotime(date('Y-m-d',$timestamp));
//            $time = date('Y-m-d H:i:s',strtotime("+$change minute",$timestamp));
//            echo "经过{$change}分钟 到{$time}（0时区）时在黄道：".number_format($sun_deg+$change/24/60*$sun[1],7)."发生精确合相1⃣️\n";
//        }
//        // 太阳1度，速度0.9   月亮356度，速度12；
//        elseif($sun_deg < $moon_deg && $sun_deg + 360 - $moon_deg <= $speed_diff)
//        {
//            $change = ceil(($sun_deg + 360  - $moon_deg) / $speed_diff * 24 * 60);//分钟数
//            $timestamp = strtotime(date('Y-m-d',$timestamp));
//            $time = date('Y-m-d H:i:s',strtotime("+$change minute",$timestamp));
//            echo "经过{$change}分钟 到{$time}（0时区）时在黄道：".number_format($sun_deg+$change/24/60*$sun[1],7)."发生精确合相1⃣️\n";
//        }
        #for debug
//        print_r($out);
//        echo "度数差：".($sun_deg - $moon_deg)." 速度差：$speed_diff\r\n\r\n\r\n\r\n";

        // 通过获取每分钟日月的度数和速度来计算新月的时间和度数  得出的度数为那一分钟起始的度数，非精确度数
        // 一天1440分钟
        $n = 1440;
        $s = '1m';
        $exec_str = config('astrolog.prefix')." -b{$utdatenow} -ut{$utnow} -p01 -eswe -fls -g,  -head -n{$n} -s{$s}";
        unset($out);
        exec ($exec_str, $out);
        $sun_arr = $moon_arr = $speed = [];
        foreach ($out as $k => $o)
        {
            $line = explode(',',$o);
            // 太阳数据
            if($k%2 == 0)
            {
                $sun_arr[] = $line[0] * 1;
            }
            // 月亮数据
            else
            {
                $moon_arr[] = $line[0] * 1;
                $speed[] = $line[1] * 1;
            }
        }

        /** @var array $sun_arr */
        foreach ($sun_arr as $k_sun => $sun)
        {
            $moon_speed = $speed[$k_sun];
            /** @var array $moon_arr */
//            echo $sun."===$k_sun====".$moon_arr[$k_sun]."\n";
            if((($sun + 360) - $moon_arr[$k_sun] <= $moon_speed/$n)
                || (abs($sun - $moon_arr[$k_sun]) <= $moon_speed/$n))
            {
                $result = $sun;
                break;
//                #for debug
//                var_dump($sun);
//                var_dump($moon_arr[$k_sun]);
//                $timestamp = strtotime(date('Y-m-d',$timestamp));
//                $time = date('Y-m-d H:i:s',strtotime("+$k_sun minute",$timestamp));
//                echo "$exec_str\n";
//                echo $sun."===$k_sun====".$moon_arr[$k_sun]."\n";
//                echo "经过{$k_sun}分钟 到{$time}（0时区）时在黄道：".$sun."发生精确合相2⃣️\n";
//                break;
            }
        }
        if($result > 360) $result -= 360;

        return $result;
    }

    public function getNow()
    {
        //1、检测当天天象
        //2、太阳在哪个星座（输出：太阳在某某座）
        //3、水、金、火、木、土是否逆行或停滞（速度低于平均速度的1/5）（输出：某星逆行，某星停滞）
        //4、日水金火木土天海冥是否与昨天24点的星座不同（输出：某某星进入某某座）
        //5、天象是否构成大十字，大风筝，大信封，大三角，T三角（输出：大十字，大风筝，大信封等）
        $tips = '';

        $time = time();

        $timeinfo = ['year'=>date('Y',$time), 'month'=>date('m',$time), 'day'=>date('d',$time), 'hour'=>0, 'minute'=>0,];

        $timeinfo['timezone'] = 8;

        $timeinfo['is_summer'] = isSummerTime($timeinfo['hour'],$timeinfo['minute'],0,$timeinfo['month'],$timeinfo['day'],$timeinfo['year']) ? 1 : 0;

//        $nowData1 = $this->getNowData($timeinfo);
        $nowData = $this->nowData;

        $tx_planet = $nowData['planets'];// 天象行星数据

        $tx_structure = $nowData['structure'];// 天象行星结构数据


        $sun_deg = $tx_planet[0]['deg'];// 太阳的度数
        $sun_speed = $tx_planet[0]['speed'];// 太阳的度数

        $start_sign = modSignId(floor($sun_deg / 30) + 1);
        $end_sign = modSignId(floor(($sun_deg + $sun_speed)/30) + 1);

        if($start_sign == $end_sign)
        {
            $sign_name = explode('|',config('astrolog.sign_name')[$start_sign])[3];

            $tips .= '太阳在'.$sign_name;
        }
        else
        {
            $sign_name = explode('|',config('astrolog.sign_name')[$end_sign])[3];

            $tips .= '太阳进入'.$sign_name;
        }

        foreach ([2,3,4,5,6] as $i)
        {
            $speed = $tx_planet[$i]['speed'];

            $average_speed = config('astrolog.speed')[$i];

            $p_name = explode('|',config('astrolog.planets_name')[$i])[3];

            if($speed < 0)
            {
                $tips .= '，'.$p_name.'逆行';
            }
            if($speed <= $average_speed/5)
            {
                $tips .= '，'.$p_name.'停滞';
            }
        }

        foreach ([2,3,4,5,6,7,8,9] as $i)
        {
            $i_deg = $tx_planet[$i]['deg'];// 太阳的度数
            $i_speed = $tx_planet[$i]['speed'];// 太阳的度数

            $i_start_sign = modSignId(floor($i_deg / 30) + 1);
            $i_end_sign = modSignId(floor(($i_deg + $i_speed)/30) + 1);

            if($i_start_sign != $i_end_sign)
            {
                $i_name = explode('|',config('astrolog.planets_name')[$i])[3];

                $i_sign_name = explode('|',config('astrolog.sign_name')[$i_end_sign])[3];

                $tips .= '，'.$i_name.'进入'.$i_sign_name;
            }
        }
        // 大十字，大风筝，大信封，大三角，T三角
        if(!empty($tx_structure['cross']))
        {
            $tips .= '，大十字';
        }
        if(!empty($tx_structure['kite']))
        {
            $tips .= '，大风筝';
        }
        if(!empty($tx_structure['envelop']))
        {
            $tips .= '，大信封';
        }
        if(!empty($tx_structure['trine']))
        {
            $tips .= '，大三角';
        }
        if(!empty($tx_structure['t_square']))
        {
            $tips .= '，T三角';
        }

        return $tips;
    }

     public function getNowlist()
    {
        //1、检测当天天象
        //2、太阳在哪个星座（输出：太阳在某某座）
        //3、水、金、火、木、土是否逆行或停滞（速度低于平均速度的1/5）（输出：某星逆行，某星停滞）
        //4、日水金火木土天海冥是否与昨天24点的星座不同（输出：某某星进入某某座）
        //5、天象是否构成大十字，大风筝，大信封，大三角，T三角（输出：大十字，大风筝，大信封等）
        $tips = '';

        $time = time();

        $timeinfo = ['year'=>date('Y',$time), 'month'=>date('m',$time), 'day'=>date('d',$time), 'hour'=>0, 'minute'=>0,];

        $timeinfo['timezone'] = 8;

        $timeinfo['is_summer'] = isSummerTime($timeinfo['hour'],$timeinfo['minute'],0,$timeinfo['month'],$timeinfo['day'],$timeinfo['year']) ? 1 : 0;

//        $nowData1 = $this->getNowData($timeinfo);
        $nowData = $this->nowData;

        $tx_planet = $nowData['planets'];// 天象行星数据

        $tx_structure = $nowData['structure'];// 天象行星结构数据


        $sun_deg = $tx_planet[0]['deg'];// 太阳的度数
        $sun_speed = $tx_planet[0]['speed'];// 太阳的度数

        $start_sign = modSignId(floor($sun_deg / 30) + 1);
        $end_sign = modSignId(floor(($sun_deg + $sun_speed)/30) + 1);

        if($start_sign == $end_sign)
        {
            $sign_name = explode('|',config('astrolog.sign_name')[$start_sign])[3];

            $tips .= '太阳在'.$sign_name;
        }
        else
        {
            $sign_name = explode('|',config('astrolog.sign_name')[$end_sign])[3];

            $tips .= '太阳进入'.$sign_name;
        }

        foreach ([2,3,4,5,6] as $i)
        {
            $speed = $tx_planet[$i]['speed'];

            $average_speed = config('astrolog.speed')[$i];

            $p_name = explode('|',config('astrolog.planets_name')[$i])[3];

            if($speed < 0)
            {
                $tips .= '，'.$p_name.'逆行';
            }
            if($speed <= $average_speed/5)
            {
                $tips .= '，'.$p_name.'停滞';
            }
        }

        foreach ([2,3,4,5,6,7,8,9] as $i)
        {
            $i_deg = $tx_planet[$i]['deg'];// 太阳的度数
            $i_speed = $tx_planet[$i]['speed'];// 太阳的度数

            $i_start_sign = modSignId(floor($i_deg / 30) + 1);
            $i_end_sign = modSignId(floor(($i_deg + $i_speed)/30) + 1);

            if($i_start_sign != $i_end_sign)
            {
                $i_name = explode('|',config('astrolog.planets_name')[$i])[3];

                $i_sign_name = explode('|',config('astrolog.sign_name')[$i_end_sign])[3];

                $tips .= '，'.$i_name.'进入'.$i_sign_name;
            }
        }
        // 大十字，大风筝，大信封，大三角，T三角
        if(!empty($tx_structure['cross']))
        {
            $tips .= '，大十字';
        }
        if(!empty($tx_structure['kite']))
        {
            $tips .= '，大风筝';
        }
        if(!empty($tx_structure['envelop']))
        {
            $tips .= '，大信封';
        }
        if(!empty($tx_structure['trine']))
        {
            $tips .= '，大三角';
        }
        if(!empty($tx_structure['t_square']))
        {
            $tips .= '，T三角';
        }

        return $tips;
    }
 public function getAstrologicalDetailst($time){
        //1、检测当天天象
        //2、太阳在哪个星座（输出：太阳在某某座）
        //3、水、金、火、木、土是否逆行或停滞（速度低于平均速度的1/5）（输出：某星逆行，某星停滞）
        //4、日水金火木土天海冥是否与昨天24点的星座不同（输出：某某星进入某某座）
        //5、天象是否构成大十字，大风筝，大信封，大三角，T三角（输出：大十字，大风筝，大信封等）
        $tips = '';

        //$time = time();

        $timeinfo = ['year'=>date('Y',$time), 'month'=>date('m',$time), 'day'=>date('d',$time), 'hour'=>date('h',$time), 'minute'=>0,];

        $timeinfo['timezone'] = 8;

        $timeinfo['is_summer'] = isSummerTime($timeinfo['hour'],$timeinfo['minute'],0,$timeinfo['month'],$timeinfo['day'],$timeinfo['year']) ? 1 : 0;

//        $nowData1 = $this->getNowData($timeinfo);
        $nowData = $this->nowData;

        $tx_planet = $nowData['planets'];// 天象行星数据

        $tx_structure = $nowData['structure'];// 天象行星结构数据


        $sun_deg = $tx_planet[0]['deg'];// 太阳的度数
        $sun_speed = $tx_planet[0]['speed'];// 太阳的度数

        $start_sign = modSignId(floor($sun_deg / 30) + 1);
        $end_sign = modSignId(floor(($sun_deg + $sun_speed)/30) + 1);


        if($start_sign == $end_sign)
        {
            $sign_name = explode('|',config('astrolog.sign_name')[$start_sign])[3];
            $tips .= '太阳在'.$sign_name;
        }
        else
        {
            $sign_name = explode('|',config('astrolog.sign_name')[$end_sign])[3];

            $tips .= '太阳进入'.$sign_name;
        }
        $timestamp0 = getEclipse($time,$timeinfo['timezone'],0);// 日食时间
        if(date('Y-m-d',$timestamp0) === date('Y-m-d',$time)){
            $tips .= $sign_name.'日食';
        }
        // $merc_deg = $tx_planet[1]['deg'];// 太阳的度数
        // $merc_speed = $tx_planet[1]['speed'];// 太阳的度数

        // $start_sign = modSignId(floor($merc_deg / 30) + 1);
        // $end_sign = modSignId(floor(($merc_deg + $merc_speed)/30) + 1);
        //  if($start_sign == $end_sign)
        // {
        //     $sign_name = explode('|',config('astrolog.sign_name')[$start_sign])[3];
        //     $tips .= '月亮在'.$sign_name;
        // }
        // else
        // {
        //     $sign_name = explode('|',config('astrolog.sign_name')[$end_sign])[3];

        //     $tips .= '月亮进入'.$sign_name;
        // }

        $merc_deg = $tx_planet[2]['deg'];// 太阳的度数
        $merc_speed = $tx_planet[2]['speed'];// 太阳的度数

        $start_sign = modSignId(floor($merc_deg / 30) + 1);
        $end_sign = modSignId(floor(($merc_deg + $merc_speed)/30) + 1);
         if($start_sign == $end_sign)
        {
            $sign_name = explode('|',config('astrolog.sign_name')[$start_sign])[3];
            $tips .= '水星在'.$sign_name;
        }
        else
        {
            $sign_name = explode('|',config('astrolog.sign_name')[$end_sign])[3];

            $tips .= '水星进入'.$sign_name;
        }


        foreach ([2,3,4,5,6,7,8,9] as $i)
        {
            $speed = $tx_planet[$i]['speed'];

            $average_speed = config('astrolog.speed')[$i];

            $p_name = explode('|',config('astrolog.planets_name')[$i])[3];

            if($speed < 0)
            {
                $tips .= '，'.$p_name.'逆行';
            }
            if($speed <= $average_speed/5)
            {
                $tips .= '，'.$p_name.'停滞';
            }
        }

        foreach ([2,3,4,5,6,7,8,9] as $i)
        {
            $i_deg = $tx_planet[$i]['deg'];// 太阳的度数
            $i_speed = $tx_planet[$i]['speed'];// 太阳的度数

            $i_start_sign = modSignId(floor($i_deg / 30) + 1);
            $i_end_sign = modSignId(floor(($i_deg + $i_speed)/30) + 1);

            if($i_start_sign != $i_end_sign)
            {
                $i_name = explode('|',config('astrolog.planets_name')[$i])[3];

                $i_sign_name = explode('|',config('astrolog.sign_name')[$i_end_sign])[3];

                $tips .= '，'.$i_name.'进入'.$i_sign_name;
            }
        }
        // 大十字，大风筝，大信封，大三角，T三角
        if(!empty($tx_structure['cross']))
        {
            $tips .= '，大十字';
        }
        if(!empty($tx_structure['kite']))
        {
            $tips .= '，大风筝';
        }
        if(!empty($tx_structure['envelop']))
        {
            $tips .= '，大信封';
        }
        if(!empty($tx_structure['trine']))
        {
            $tips .= '，大三角';
        }
        if(!empty($tx_structure['t_square']))
        {
            $tips .= '，T三角';
        }

        return $tips;
}

}
